<template>
  <div class="app-container">
    <div class="block">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="listQuery.name" placeholder="请输入角色名称"></el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="success" icon="el-icon-search" @click.native="search">{{
            $t('button.search')
          }}</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click.native="reset">{{
            $t('button.reset')
          }}</el-button>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :span="24">
          <el-button type="success" icon="el-icon-plus" @click.native="add">{{
            $t('button.add')
          }}</el-button>
          <el-button type="primary" icon="el-icon-edit" @click.native="edit">{{
            $t('button.edit')
          }}</el-button>
          <el-button type="danger" icon="el-icon-delete" @click.native="remove">{{
            $t('button.delete')
          }}</el-button>
          <el-button type="primary" icon="el-icon-setting" @click.native="openPermissions"
            >权限配置</el-button
          >
        </el-col>
      </el-row>
    </div>

    <el-table
      :data="list"
      v-loading="listLoading"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @current-change="handleCurrentChange"
    >
      <el-table-column label="名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="编码">
        <template slot-scope="scope">
          {{ scope.row.tips }}
        </template>
      </el-table-column>
      <el-table-column label="所在部门">
        <template slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
      </el-table-column>
      <el-table-column label="上级角色">
        <template slot-scope="scope">
          {{ scope.row.pName }}
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100, 500]"
      :page-size="listQuery.limit"
      :total="total"
      @size-change="changeSize"
      @current-change="fetchPage"
      @prev-click="fetchPrev"
      @next-click="fetchNext"
    >
    </el-pagination>

    <el-dialog :title="formTitle" :visible.sync="formVisible" width="70%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编码" prop="tips">
              <el-input v-model="form.tips" minlength="1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" minlength="1"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="上级角色">
              <el-input
                placeholder="请选择上级角色"
                v-model="form.pName"
                readonly="readonly"
                @click.native="roleTree.show = !roleTree.show"
              >
              </el-input>
              <el-tree
                v-if="roleTree.show"
                empty-text="暂无数据"
                :expand-on-click-node="false"
                :data="list"
                :props="roleTree.defaultProps"
                @node-click="handleRoleNodeClick"
                class="input-tree"
              >
              </el-tree>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input v-model="form.num" type="number"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所在部门">
              <el-input
                placeholder="请选择所在部门"
                v-model="form.deptName"
                readonly="readonly"
                @click.native="deptTree.show = !deptTree.show"
              >
              </el-input>
              <el-tree
                v-if="deptTree.show"
                empty-text="暂无数据"
                :expand-on-click-node="false"
                :data="deptList"
                :props="deptTree.defaultProps"
                @node-click="handleDeptNodeClick"
                class="input-tree"
              >
              </el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="save">{{ $t('button.submit') }}</el-button>
          <el-button @click.native="formVisible = false">{{ $t('button.cancel') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="权限配置" :visible.sync="permissonVisible" width="25%">
      <el-form>
        <el-row>
          <el-col :span="12">
            <el-tree
              :data="permissons"
              ref="permissonTree"
              show-checkbox
              node-key="id"
              :default-checked-keys="checkedPermissionKeys"
              :props="defaultProps"
            >
            </el-tree>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="savePermissions">{{ $t('button.submit') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { remove, getList, save, savePermissons } from '@/api/system/role';
import { list as getDeptList } from '@/api/system/dept';
import { menuTreeListByRoleId } from '@/api/system/menu';

export default {
  data() {
    return {
      formVisible: false,
      formTitle: '添加角色',
      deptList: [],
      roleList: [],
      isAdd: true,
      checkedPermissionKeys: [],
      permissons: [],
      defaultProps: {
        id: 'id',
        label: 'name',
        children: 'children',
      },
      permissonVisible: false,
      deptTree: {
        show: false,
        defaultProps: {
          id: 'id',
          label: 'simplename',
          children: 'children',
        },
      },
      roleTree: {
        show: false,
        defaultProps: {
          id: 'id',
          label: 'name',
          children: 'children',
        },
      },

      form: {
        tips: '',
        name: '',
        deptid: '',
        pid: 0,
        id: '',
        version: '',
        deptName: '',
        pName: '',
        num: 1,
      },
      rules: {
        tips: [
          { required: true, message: '请输入角色编码', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
        ],
      },
      listQuery: {
        name: undefined,
      },
      total: 0,
      list: null,
      listLoading: true,
      selRow: {},
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger',
      };
      return statusMap[status];
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      getDeptList().then((response) => {
        this.deptList = response.data;
      });
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      getList(this.listQuery).then((response) => {
        console.log(response.data);
        this.list = response.data;
        this.listLoading = false;
        this.total = response.data.total;
      });
    },
    search() {
      this.fetchData();
    },
    reset() {
      this.listQuery.name = '';
      this.fetchData();
    },
    handleFilter() {
      this.getList();
    },
    fetchNext() {
      this.listQuery.page = this.listQuery.page + 1;
      this.fetchData();
    },
    fetchPrev() {
      this.listQuery.page = this.listQuery.page - 1;
      this.fetchData();
    },
    fetchPage(page) {
      this.listQuery.page = page;
      this.fetchData();
    },
    changeSize(limit) {
      this.listQuery.limit = limit;
      this.fetchData();
    },
    handleCurrentChange(currentRow) {
      this.selRow = currentRow;
    },
    resetForm() {
      this.form = {
        tips: '',
        name: '',
        deptid: '',
        pid: 0,
        id: '',
        version: '',
        deptName: '',
        pName: '',
        num: 1,
      };
    },
    add() {
      this.resetForm();
      this.formTitle = '添加角色';
      this.formVisible = true;
      this.isAdd = true;
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          save({
            id: this.form.id,
            num: this.form.num,
            deptid: this.form.deptid,
            pid: this.form.pid,
            name: this.form.name,
            tips: this.form.tips,
          }).then(() => {
            this.$message({
              message: '提交成功',
              type: 'success',
            });
            this.fetchData();
            this.formVisible = false;
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    checkSel() {
      if (this.selRow && this.selRow.id) {
        return true;
      }
      this.$message({
        message: '请选中操作项',
        type: 'warning',
      });
      return false;
    },
    edit() {
      if (this.checkSel()) {
        this.isAdd = false;
        this.form = this.selRow;
        this.form.status = this.selRow.statusName === '启用';
        this.form.password = '';
        this.formTitle = '修改角色';
        this.formVisible = true;
      }
    },
    remove() {
      if (this.checkSel()) {
        const id = this.selRow.id;
        this.$confirm('确定删除该记录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            remove(id)
              .then(() => {
                this.$message({
                  message: '提交成功',
                  type: 'success',
                });
                this.fetchData();
              })
              .catch((err) => {
                this.$notify.error({
                  title: '错误',
                  message: err,
                });
              });
          })
          .catch(() => {});
      }
    },
    openPermissions() {
      if (this.checkSel()) {
        menuTreeListByRoleId(this.selRow.id).then((response) => {
          this.permissons = response.data.treeData;
          this.checkedPermissionKeys = response.data.checkedIds;
          this.permissonVisible = true;
        });
      }
    },
    savePermissions() {
      let checkedNodes = this.$refs.permissonTree.getCheckedNodes(false, true);
      let menuIds = '';
      for (var index in checkedNodes) {
        menuIds += checkedNodes[index].id + ',';
      }
      const data = {
        roleId: this.selRow.id,
        permissions: menuIds,
      };
      savePermissons(data).then(() => {
        this.permissonVisible = false;
        this.$message({
          message: '提交成功',
          type: 'success',
        });
      });
    },
    handleDeptNodeClick(data) {
      this.form.deptid = data.id;
      this.form.deptName = data.simplename;
      this.deptTree.show = false;
    },
    handleRoleNodeClick(data) {
      this.form.pid = data.id;
      this.form.pName = data.name;
      this.roleTree.show = false;
    },
  },
};
</script>
<style lang="scss" scoped>
@import '~@/styles/common.scss';
</style>
